import pygame
import keyboard
import msvcrt #仅用于windows系统
import custom_mouse
import math
import os
import json

def refresh_options(prompt):
    match prompt:
        case "请选择手柄编号: ":
            pygame.joystick.quit()
            pygame.joystick.init()
            return [pygame.joystick.Joystick(x).get_name() for x in range(pygame.joystick.get_count())]

def let_you_choose(prompt, options: list):
    if options is None or len(options) == 0:
        print(f"{prompt}\033[31m没有可选项。检查设备后按回车重试\033[0m")
        keyboard.wait('enter')
        return let_you_choose(prompt, refresh_options(prompt))

    for option in options:
        print(f"\033[31m{options.index(option)}\033[0m - {option}")
    print(prompt, end=" ")

    if len(options) == 1:
        selected_index = 0
        print(f"\033[32m{selected_index} - {options[selected_index]}\033[0m(只有一个选项, 自动选择)\n")
        return selected_index
    while True:
        event = keyboard.read_event()
        if event.event_type == 'up':
            try:
                selected_index = int(event.name)
                if selected_index < len(options):
                    break
            except:
                pass
    print(f"\033[32m{selected_index} - {options[selected_index]}\033[0m\n")
    clear_input_buffer()
    return selected_index

def clear_input_buffer():
    while msvcrt.kbhit():
        msvcrt.getch()

def read_or_create_config():
    config_file = 'config.json'
    
    global default_config
    default_config = {
        "sensitiivty": 200,
        "deadzone": 0.4,
        "k": 3
    }
    
    # 如果config.json文件存在，读取配置
    if os.path.exists(config_file):
        with open(config_file, 'r') as f:
            config = json.load(f)
            return config
    else:
        # 创建默认配置文件
        with open(config_file, 'w') as f:
            json.dump(default_config, f, indent=4)
        return default_config

config = read_or_create_config()
deadzone = config["deadzone"]
sensitiivty = config["sensitiivty"]
s = sensitiivty
k = config["k"]
pygame.init()
pygame.joystick.init()
selected_gamepad = pygame.joystick.Joystick(let_you_choose("请选择手柄编号: ", [pygame.joystick.Joystick(x).get_name() for x in range(pygame.joystick.get_count())]))
selected_gamepad.init()

L_stick =(0,1)
R_stick =(2,3)
selected_stick = L_stick

before_a = (0,0) # 记录上一次的摇杆坐标值

while True:
    for event in pygame.event.get([pygame.JOYAXISMOTION]):
        a = (selected_gamepad.get_axis(selected_stick[0]) , selected_gamepad.get_axis(selected_stick[1]))
        if (a[0]**2 + a[1]**2) > deadzone**2:
            if a[1]==0 and a[0]<0: # 跳过临界条件
                continue

            if selected_gamepad.get_button(4) or selected_gamepad.get_button(5): # bumper_button
                s = int(sensitiivty*k)
            else:
                s = int(sensitiivty)

            if a[1]*before_a[1] <= 0 and a[0] < 0: # 旋转一圈，即pi、-pi突变
                if a[1]<0:   # 逆时针
                    custom_mouse.move_mouse(int((math.atan2(a[1], a[0])/math.pi*s)) - int(math.atan2(before_a[1], before_a[0])/math.pi*s) + 2*s, 0)
                else:   # 顺时针
                    custom_mouse.move_mouse(int((math.atan2(a[1], a[0])/math.pi*s)) - int(math.atan2(before_a[1], before_a[0])/math.pi*s) - 2*s, 0)
            else:
                custom_mouse.move_mouse(int((math.atan2(a[1], a[0])/math.pi*s)) - int(math.atan2(before_a[1], before_a[0])/math.pi*s), 0)

            before_a = a
 